package cn.bocweb.spinning.view.common;

import android.support.v4.widget.SwipeRefreshLayout;
import android.widget.AbsListView;

import cn.bocweb.spinning.R;


/**
 * Created by Kaizen on 2015/9/16.
 */
public class SwipeRefreshHelper {

    public interface OnSwipeRefreshListener {

        void onRefresh();

        void onLoad();
    }

    public static final int REFRESH = 0;
    public static final int LOAD = 1;
    public static final int EMPTY = 2;
    private SwipeRefreshLayout swipeRefreshLayout;
    private AbsListView listView;
    private OnSwipeRefreshListener mOnSwipeRefreshListener;
    private int mCurrentStatus = 0;

    public SwipeRefreshHelper(SwipeRefreshLayout swipeRefreshLayout,
                              final AbsListView listView,
                              OnSwipeRefreshListener onSwipeRefreshListener) {
        this.listView = listView;
        this.swipeRefreshLayout = swipeRefreshLayout;
        this.mOnSwipeRefreshListener = onSwipeRefreshListener;
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(
                    R.color.colorPrimary
            );

            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    mCurrentStatus = REFRESH;
                    mOnSwipeRefreshListener.onRefresh();
                }
            });
        }

        if (listView != null) {
            listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    switch (scrollState) {
                        case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                            if (mCurrentStatus != EMPTY) {
                                if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                                    mCurrentStatus = LOAD;

                                    mOnSwipeRefreshListener.onLoad();
                                }
                            }
                            break;
                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                }
            });
        }

    }

    public int getCurrentStatus() {
        return mCurrentStatus;
    }

    public void setStatus(int status) {
        mCurrentStatus = status;
    }

}
